import logging

import pytest

from resource.pom.contacts import Contacts
from resource.pom.keyboard import Keyboard
from utils.manager import Images


@pytest.fixture(autouse=True)
def preset_contactor(device):
    logging.info('方法前置----预置联系人')
    Contacts.create_contactor(device)
    yield
    logging.info('方法后置----删除联系人')
    Contacts.delete_contactor(device)


class Test:
    app = Contacts
    keyboard = Keyboard

    @pytest.mark.parametrize('setup_teardown', [app.bundle_name], indirect=True)
    def test(self, setup_teardown, device):
        logging.info('步骤1.点击联系人应用')
        device.start_ability(self.app.bundle_name, self.app.ability_name)
        logging.info('预期结果1.正常进入联系人应用内')
        device.assert_current_window(self.app.window_name)

        logging.info('步骤2、点击切换到联系人列表页')
        device.click(*self.app.menu_contacts)
        logging.info('预期结果2、成功切换到联系人列表页')
        device.refresh_layout()
        device.assert_text_exist(self.app.test_name)

        logging.info('步骤3、长按单个联系人后点击删除，依次删除至列表为空')
        contact = device.get_element_by_text(self.app.test_name)
        device.long_click_element(contact)
        device.refresh_layout()
        menu = device.get_element_by_type('Menu')
        menu_area = device.get_element_area(menu)
        menu_pic = device.save_snapshot_to_local('del_menu.jpeg')
        Images.crop_picture(menu_pic, *menu_area)
        similarity = Images.compare_image_similarity(menu_pic, self.app.standard_del_menu, threshold=5)
        assert similarity > 0.6, '删除弹窗显示异常，请手工复测确认'
        delete_btn = device.get_element_by_text('删除')
        device.click_element(delete_btn)
        device.refresh_layout()
        delete_dialog = device.get_element_by_text('删除')
        device.click_element(delete_dialog)
        logging.info('预期结果3、联系人列表清空后显示“新建联系人”界面')
        device.refresh_layout()
        device.assert_text_exist('新建联系人')
